又要擴充node_module了,這次請在終端輸入npm install socket.io
,以安裝socket.io。然後,在原先的index.js中修改幾筆,使之變成—
const express = require('express');
const app = express();
// This part is new!
const http = require('http');
const server = http.createServer(app);
const { Server } = require('socket.io');
const io = new Server(server);
const PORT = 3000;
io.on('connection', (socket) => {
console.log("User is connected")
socket.on('disconnect', () => {
console.log('User disconnected');
});
})
app.use("/", express.static("public"));
// It is no longer app.listen()!
server.listen(PORT, () => console.log(`Server listening on port: ${PORT}`));
客戶端比較容易,參考官方網站,我們只需利用CDN就可將socket.io放在網頁上。完成後的index.html像這樣:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>零碳運算</title>
</head>
<body>
<h1>零碳運算</h1>
<input></input>
<input type="button" value="send"></input>
<!-- socket.io from CDN -->
<script src="https://cdn.socket.io/4.6.0/socket.io.min.js"
integrity="sha384-c79GN5VsunZvi+Q/WObgk2in0CbZsHnjEqvFxC5DxHn9lTfNce2WW6h2pH6u/kF+"
crossorigin="anonymous"></script>
<!-- our client-side script -->
<script src="script.js" defer></script>
</body>
</html>
然後,我們便可以在script.js 中加入socket.io的接通咒語。const socket = io();
就是這樣,就接通了互聯網的另一端—你可以在伺服器的終端實時看到客戶端的人何時連接,何時斷開,這已超越了以往倚賴HTTP通訊所能做的了。